package com.saicmotor.paging3;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.paging.PagingSource;
import androidx.paging.PagingState;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import kotlin.coroutines.Continuation;

/**
 * @Author xinxinzhang
 * @Date 2022/08/17
 **/
public class Paging3DataSource extends PagingSource<Integer, ArticleBean.DataBean.DatasBean> {


    @Nullable
    @Override
    public Object load(@NotNull LoadParams<Integer> params, @NotNull Continuation<? super LoadResult<Integer, ArticleBean.DataBean.DatasBean>> continuation) {
        int page = 0;
        if(params.getKey()!=null){
            page=params.getKey();
        }
        //获取网络数据
        WanAndroidApi api=RetrofitClient.getInstance().createApi(WanAndroidApi.class);
        ArticleBean result =(ArticleBean)api.getArticleList(page);
        //需要加载的数据
        List<ArticleBean.DataBean.DatasBean> datas= result.getData().getDatas();
        //如果可以往上加载更多就设置该参数，否则不设置
        String prevKey=null;
        //加载下一页的key 如果传null就说明到底了
        String nextKey=null;
        if(result.getData().getCurPage() == result.getData().getPageCount()){
            nextKey=null;
        }else {
            nextKey=String.valueOf(page+1);
        }
        return new LoadResult.Page<>(datas,prevKey,nextKey);
    }


    @Nullable
    @Override
    public Integer getRefreshKey(@NonNull PagingState<Integer, ArticleBean.DataBean.DatasBean> pagingState) {
        return null;
    }
}